package com.jingyuan.biz.event.listener;

import com.jingyuan.biz.event.VoteEvent;
import com.jingyuan.biz.manager.JNode;
import com.jingyuan.biz.manager.JNodeManager;
import com.jingyuan.common.entity.EventType;
import com.jingyuan.common.entity.HostInfo;
import com.jingyuan.common.entity.ServerMessage;
import com.jingyuan.common.entity.packet.ServerMessageType;
import io.netty.channel.Channel;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * 选举事件监听器
 */
@Service
public class VoteListener extends EventListener<VoteEvent> {
    @Resource
    private JNodeManager nodeManager;

    public VoteListener(){
        this.setListenEventType(EventType.VOTE);
    }
    @Override
    public void actionListener(VoteEvent event) {
        int phase=event.getPhase();
        JNode eventNode=event.getNode();
        List<JNode> nodeList=nodeManager.getHostNode();
        if(phase==VoteEvent.VOTE_START){
            ServerMessage message=new ServerMessage();
            message.setServerMessageType(ServerMessageType.VOTING_START);
            message.setMsg("-----------------------开始选举过程---------------------");
            for(JNode node:nodeList){
                Channel channel=node.getChannel();
                channel.writeAndFlush(message);
            }
        }else if(phase==VoteEvent.VOTE_END){
            ServerMessage message=new ServerMessage();
            HostInfo hostInfo=new HostInfo();
            hostInfo.setAddress(event.getAddress());
            hostInfo.setPort(event.getPort());
            message.setHost(hostInfo);
            message.setMsg(String.format("-----------------------选举过程结束,新master节点地址为:%s---------------------",event.getAddress()));
            message.setServerMessageType(ServerMessageType.VOTING_END);
            for(JNode node:nodeList){
                Channel channel=node.getChannel();
                channel.writeAndFlush(message);
            }
        }else if(phase==VoteEvent.VOTE_NOW){
            ServerMessage message=new ServerMessage();
            message.setServerMessageType(ServerMessageType.VOTING_NOW);
            message.setMsg("-----------------------正在进行选举---------------------");
            Channel channel=event.getNode().getChannel();
            channel.writeAndFlush(message);
        }else{
            event.setVoteValue(event.getVoteValue());
        }
    }
}
